//
//  NewMainVC.m
//  QoilPublic
//
//  Created by SunChao on 2018/1/12.
//  Copyright © 2018年 孙超. All rights reserved.
//

#import "NewMainVC.h"
#import "NewMainHeadView.h"
#import "NewMainMidView.h"
#import "NewMainBottomView.h"
#import "QMainModel.h"
#import "MJExtension.h"
#import "QTopupMoneyVC.h"
#import "QPerfectOrderInforMationVC.h"
#import "QLoginVC.h"
#import <AMapLocationKit/AMapLocationKit.h>
#import <AMapSearchKit/AMapSearchKit.h>
#import "QNoPayOrderModel.h"
#import "UITabBar+badge.h"
#import "QActiveWebViewVC.h"
#import "AddressVC.h"
#import "HomePingJiaVC.h"
#import "PingJiaSuccessVC.h"
#import "IOTVC.h"
@interface NewMainVC ()<AddOilOrChargeDelegate,AMapLocationManagerDelegate,AMapSearchDelegate,UITableViewDataSource,UITableViewDelegate>

@property (nonatomic, strong) AMapLocationManager *locationManager;

@property (nonatomic, strong) AMapSearchAPI *search;

@property (nonatomic,strong) NewMainHeadView *headView;
@property (nonatomic,strong) NewMainMidView *midView;
@property (nonatomic,strong) NewMainBottomView *bottomView;
@property (nonatomic,strong) NSMutableArray *imgvoArr;//轮播的所有数据
@property (nonatomic,strong) NSMutableArray *newsArr;//最新优惠消息
@property (nonatomic,strong) NSMutableArray *bottomArray;
@property (nonatomic,strong)UITableView *tbView;
@end

@implementation NewMainVC
-(void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    [self.navigationController  setNavigationBarHidden:YES animated:animated];
}
- (void)viewDidAppear:(BOOL)animated{
    
    [super viewDidAppear:animated];
   
}

- (void)gainOrderInfo{
    
    NSString *url = [QParamService urlWithAction:@"order/findUserOrderEvaluate"];
    NSDictionary *params = [QParamService GainStarText];
    
    [[QHttpManager sharedManager] POST:url parameterMD5:params completion:^(NSData *data, NSDictionary *dict, NSError *error) {
        if(error){
            
            return ;
        }
        QBaseModel *basModel = [QBaseModel objectFromDict:dict];
        
        if([basModel.result isEqualToString:@"success"]){
            
            NSArray *array = basModel.items;
            NSLog(@"array:%@",basModel.items);
            if (array.count>0 ) {
                
                HomePingJiaVC *vc = [[HomePingJiaVC alloc]init];
                
                UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:vc];
                nav.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
                [self presentViewController:nav animated:YES completion:nil];
                
            }else{
                
//                PingJiaSuccessVC *vc = [[PingJiaSuccessVC alloc]init];
//
//                UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:vc];
//                nav.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
//                [self presentViewController:nav animated:YES completion:nil];
            }
            
        }else{
            
        }
    }];
}

- (void)viewWillDisappear:(BOOL)animated{
    
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}
- (UITableView *)tbView{
    
    if (!_tbView) {
        _tbView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
        _tbView.delegate = self;
        _tbView.dataSource = self;
       _tbView.separatorStyle = UITableViewCellSeparatorStyleNone;
        if (@available(iOS 11.0, *)) {
            self.tbView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        } else {
            self.automaticallyAdjustsScrollViewInsets = NO;
        }
    }
    
    return _tbView;
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notifiAction:) name:kNotificationRegisterSuccess object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationLoginSignupAction) name:kNotificationTopUpMoneySuccess object:nil];//支付宝充值成功通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pushToAdVC) name:kNotificationPushToAdVC object:nil];//启动页广告走向
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(requestNoPayOrderData) name:kNotificationNoPayOrders object:nil];//未支付订单
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationLoginSignOutAction) name:kNotificationLoginSignOut object:nil];//退出登录通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationLoginSignupAction) name:kNotificationLoginSignup object:nil];//登陆成功通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationTabBarAction) name:kNotificationTabBar1 object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationLoginSignupAction) name:@"PaySuccessNotification" object:nil];
    [self  createUI];
    [self requestData];//获取轮播数据
   
    [self setLocationManager];//地图定位

}
- (void)notificationTabBarAction{
    
    [self requestData];
    
}
- (void)notificationLoginSignOutAction{
    
    [_midView setStatusWithIsLogin:NO AccountMoney:@""];
}
- (void)notificationLoginSignupAction{
    
    [self requestDataMySelf];
    
}
- (void)pushToAdVC{
    
    NSString *url = [[NSUserDefaults standardUserDefaults] valueForKey:@"adUrl"];
    if (url.length>0) {
        QActiveWebViewVC  *vc = [[QActiveWebViewVC alloc] init];
        vc.url =url;
        [self.navigationController pushViewController:vc animated:YES];
    }
}
#pragma mark --- 是否有订单未支付
- (void)requestNoPayOrderData{
    NSString *url = [QParamService urlWithAction:@"getOrderStateNum"];
    NSDictionary *param = [QParamService noPayOrder];
    [[QHttpManager sharedManager] POST:url parameterMD5jm:param completion:^(NSData *data, NSDictionary *dict, NSError *error) {
        if(error){
            return;
        }
        QBaseModel *basModel = [QBaseModel objectFromDict:dict];
        if([basModel.result isEqualToString:@"success"]){
            QNoPayOrderModel * model = [QNoPayOrderModel objectFromDict:basModel.items];
            if ([model.num isEqualToString:@"0"]) {
                [QUserInfo sharedInfo].unPayOrder = NO;
                
            }else{
                [QUserInfo sharedInfo].unPayOrder = YES;
                [QUserInfo sharedInfo].unPayCount = [NSString stringWithFormat:@"%@",model.num];
            }
        }else{
        }
    }];
    
    [self requestUnlookMessage];
}

#pragma mark --- 是否有未读消息
- (void)requestUnlookMessage{
    NSString *UUID = [QParamService getUUID];
    NSString *url = [QParamService urlWithAction:@"getIsUnLook"];
    NSDictionary *param = [QParamService getIsUnLookWithMac:UUID];
    [[QHttpManager sharedManager] POST:url parameterMD5jm:param completion:^(NSData *data, NSDictionary *dict, NSError *error) {
        if(error){
            return ;
        }
        QBaseModel *basModel = [QBaseModel objectFromDict:dict];
        if([basModel.result isEqualToString:@"success"]){
            NSString * size = basModel.items[@"size"];
            if ([size isEqualToString:@"0"]) {
                [self.tabBarController.tabBar hideBadgeOnItemIndex:2];
            }else{
                [self.tabBarController.tabBar showBadgeOnItemIndex:2];
            }
            
        }else{
        }
    }];
    
}
- (void)notifiAction:(NSNotification *)notification{
    
    [self requestDataMySelf];
    
}

#pragma mark --- 更新用户登陆数据
- (void)requestDataMySelf{
    NSString *url = [QParamService urlWithAction:@"myCentre"];
    NSDictionary *param = [QParamService getMyCentreData:@"2"];
    [[QHttpManager sharedManager] POST:url parameterMD5:param completion:^(NSData *data, NSDictionary *dict, NSError *error) {
        if(error){
            return ;
        }
        QBaseModel *basModel = [QBaseModel objectFromDict:dict];
        if([basModel.result isEqualToString:@"success"]){
            QLoginModel *loginModel = [QLoginModel objectFromDict:basModel.items];
            [QDataUtility updateLoginModel:loginModel];
            [_midView setStatusWithIsLogin:YES AccountMoney:loginModel.balance];
        }else{
            [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"cry_image"] content:basModel.errMsg btnTitle:showAlertBtnTitle type:1 myBlock:^{}];
            if([basModel.errMsg isEqualToString:@"请重新登录"]){
                [QDataUtility deleteLoginModel];
            }
        }
    }];
}
- (void)createUI{

    [self.view addSubview:self.tbView];
   _headView  = [[NewMainHeadView alloc]init];
    _headView.frame = CGRectMake(0, 0, kScreenWidth, 230);
    self.tbView.tableHeaderView = _headView;
    UIButton *phonebtn = [[UIButton alloc] initWithFrame:CGRectMake(15, kStatusHeight, 32, 32)];
    [phonebtn setImage:[UIImage imageNamed:@"home_phone"] forState:0];
    [phonebtn addTarget:self action:@selector(navAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:phonebtn];
    
    _midView = [[NSBundle mainBundle]loadNibNamed:@"NewMainMidView" owner:nil options:nil].lastObject;
    
   
    _midView.delegate = self;
 [_midView setStatusWithIsLogin:[QUserInfo sharedInfo].loginModel AccountMoney:[QUserInfo sharedInfo].loginModel.balance];
    NSArray *objs3 = [[NSBundle mainBundle]loadNibNamed:@"NewMainBottomView" owner:nil options:nil];
    _bottomView = objs3.firstObject;
}
#pragma mark --获取轮播图数据
- (void)requestData{
    NSString *url = [QParamService urlWithAction:@"homepage"];
    [QViewUtility showMBHudToView:self.view hideBg:NO];
    [[QHttpManager sharedManager] POST:url parameters:nil completion:^(NSData *data, NSDictionary *dict, NSError *error) {
        [QViewUtility hideMBHudToView:self.view];
        if(error){
            if([QUserInfo sharedInfo].isHaveNetWork == NO){
                [QViewUtility showNoNetWorkInView:self.view];
            }
            return ;
        }
        [QViewUtility disMissNoNetWorkInVC:self];
        QBaseModel *basModel = [QBaseModel objectFromDict:dict];
        if([basModel.result isEqualToString:@"success"]){
            [_imgvoArr removeAllObjects];
            [_newsArr removeAllObjects];
            _imgvoArr = basModel.items[@"imgvoList"];//***********************所有轮播数据
            _newsArr = basModel.items[@"activityList"];
            [_headView setImageWithData:_imgvoArr];
            [_bottomView setNewsWithData:_newsArr];

             [self RequestBannerData];//获取banner数据
        }else{
            [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"cry_image"] content:basModel.errMsg btnTitle:showAlertBtnTitle type:1 myBlock:^{}];
        }
    }];
}

/**
 首页菜单配置
 积分商城 ：sort：”1”
 积分签到 ：sort：”2”
 设备管理 ：sort：”3”
 推荐有奖 ：sort：”4”
 邀请好友 ：sort：”5”
 */
#pragma mark ---获取后台动态配置
- (void)RequestBannerData{
    NSString *url = [QParamService urlWithAction:@"usercard/getMenuConfig"];
    NSDictionary *param = [QParamService getUsercard];
    
    [QViewUtility showMBHudToView:self.view hideBg:NO];
    [[QHttpManager sharedManager] POST:url parameterMD5:param completion:^(NSData *data, NSDictionary *dict, NSError *error) {
        [QViewUtility hideMBHudToView:self.view];
        if(error){
            
            if([QUserInfo sharedInfo].isHaveNetWork == NO){
                
                [QViewUtility showNoNetWorkInView:self.view];
                
            }
            return ;
        }
        [QViewUtility disMissNoNetWorkInVC:self];
        QBaseModel *basModel = [QBaseModel objectFromDict:dict];
        if([basModel.result isEqualToString:@"success"]){
            
            NSDictionary *tmpDic = [dict objectForKey:@"items"];
            
            NSLog(@"tmpDic:%@",tmpDic);
            
            //NSArray *array = [tmpDic objectForKey:@"list"];
            NSArray *array =  [QMainModel mj_objectArrayWithKeyValuesArray:[basModel.items objectForKey:@"list"]];
            [self.bottomArray removeAllObjects];
            //只执行一次
            static dispatch_once_t loadPingJia;
            dispatch_once(&loadPingJia, ^{
                [self gainOrderInfo];
            });
            if (array.count>0) {
                for (QMainModel *model in array) {
                    NSString *type = model.type;
                    NSString *isDisplay = model.isDisplay;
                    if ([type isEqualToString:@"1"]&&[isDisplay isEqualToString:@"0"]) {
                       
                        [self.bottomArray addObject:model];
                        
                    }
                }
                
            }

            if (self.bottomArray.count>0) {
                 [_bottomView setBannerWithData:self.bottomArray];
           
            }
            
            
        }else{
            
        }
    }];
    
}

#pragma mark ---打电话点击方法
- (void)navAction:(UIButton *)btn{
    
    [QViewUtility showPlayBoxView:PlayboxCallPhoneStyle myBlock:^(NSInteger index) {
        if(index == 1){
            [QViewUtility callPhone];
        }
    }];
}


- (void)DidSelectedButtonAtIndex:(NSInteger)index{
    
    
    if (![QUserInfo sharedInfo].loginModel) {
         [self notLogin];
        return;
    }
    if (index == 2) {//充值
       
    QTopupMoneyVC *vc = [[QTopupMoneyVC alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
   
    }
    if (index == 1) {//加油
        
        [self pushToNextVC];
    }
    if (index == 3) {//智能加油
        
        
        [self requestIOTData];//判断是否有云盒子设备
//        [self requestUserAccountData];//智能加油申请
//        IOTVC *vc = [[IOTVC alloc]init];//云盒子
//        [self.navigationController pushViewController:vc animated:YES];
//        IOTMapVC *vc = [[IOTMapVC alloc]init];
//        [self.navigationController pushViewController:vc animated:YES];
    }
    
}
- (void)requestIOTData{
    NSString *url = [QParamService urlWithIOTAction:@"userDevice/ifDevice"];
    
    NSString *token = [QParamService getToken];
    NSDictionary *param = @{@"token":token};
    [QViewUtility showMBHudToView:self.view hideBg:NO];
    [[QHttpManager sharedManager] POST:url parameterMD5:param completion:^(NSData *data, NSDictionary *dict, NSError *error) {
        [QViewUtility hideMBHudToView:self.view];
        
        if(error){
            
            return ;
            
        }
        QBaseModel *basModel = [QBaseModel objectFromDict:dict];
        if([basModel.result isEqualToString:@"success"]){
            
            NSDictionary *dict =  basModel.items;
            if ([[dict objectForKey:@"ifDevice"]isEqualToString:@"true"]) {
                
                IOTVC *vc = [[IOTVC alloc]init];//云盒子
                
                [self.navigationController pushViewController:vc animated:YES];
              
                return;
            }
            
            if ([[dict objectForKey:@"ifDevice"]isEqualToString:@"false"]) {
                
               NSString *url =  [dict objectForKey:@"url"];
                QActiveWebViewVC *webVC  = [[QActiveWebViewVC alloc]init];
                webVC.url = url;
                [self.navigationController pushViewController:webVC animated:YES];
                
            }
//            [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"cry_image"] content:@"您还没有云盒子设备" btnTitle:showAlertBtnTitle type:1 myBlock:^{}];
          
        }else{
            
            [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"cry_image"] content:@"请求失败" btnTitle:showAlertBtnTitle type:1 myBlock:^{}];
            
        }
    }];
    
}
- (void)requestUserAccountData{
    
    NSString *url = [QParamService urlWithAction:@"userinfo/findUir"];
    
    NSDictionary *param = [QParamService GainStarText];
    
    [QViewUtility showMBHudToView:self.view hideBg:NO];
    [[QHttpManager sharedManager] POST:url parameterMD5:param completion:^(NSData *data, NSDictionary *dict, NSError *error) {
        [QViewUtility hideMBHudToView:self.view];
        
        if(error){
            
            return ;
            
        }
        QBaseModel *basModel = [QBaseModel objectFromDict:dict];
        if([basModel.result isEqualToString:@"success"]){
           
            NSArray *array =  basModel.items;
            NSDictionary *dic = [array objectAtIndex:0];
           NSString *isRegister =  [dic objectForKey:@"existence"];
            if ([isRegister isEqualToString:@"true"]) {
                
                [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"smile_image"] content:@"已提交智能加油申请" btnTitle:showAlertBtnTitle type:1 myBlock:^{}];
                
            }
            if ([isRegister isEqualToString:@"false"]) {
                
                 [self pushToBusVC];
            }
        
        }else{
            
            [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"cry_image"] content:@"请求失败" btnTitle:showAlertBtnTitle type:1 myBlock:^{}];
            
        }
    }];
    
}

- (void)pushToBusVC{
    
    if ([QUserInfo sharedInfo].loginModel) {
        if ([QUserInfo sharedInfo].unPayOrder == YES) {
            NSString *title = [NSString stringWithFormat:@"您有%@个订单尚未支付",[QUserInfo sharedInfo].unPayCount];
            [QViewUtility showAlertChooseViewWithImage:[UIImage imageNamed:@"smile_image"] content:title leftTitle:@"继续下单" rightTitle:@"去支付" type:1 myBlock:^(NSInteger tag) {
                if(tag == 1){
                    
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"kNotificationGoToPay" object:nil];
                    self.tabBarController.selectedIndex = 1;
                    
                }else if (tag == 0){
                    QPerfectOrderInforMationVC *vc = [[QPerfectOrderInforMationVC alloc] init];
                    [self.navigationController pushViewController:vc animated:YES];
                    vc.nopaycount = [QUserInfo sharedInfo].unPayCount;
                }
            }];
        }else{
            
            //跳转加油地址填写页面
            
            AddressVC *addVC = [[AddressVC alloc]init];
            
            [self.navigationController pushViewController:addVC animated:YES];
            
        }
    }
}

- (void)pushToNextVC{
    if([QUserInfo sharedInfo].loginModel){
        if ([QUserInfo sharedInfo].unPayOrder == YES) {
            NSString *title = [NSString stringWithFormat:@"您有%@个订单尚未支付",[QUserInfo sharedInfo].unPayCount];
            [QViewUtility showAlertChooseViewWithImage:[UIImage imageNamed:@"smile_image"] content:title leftTitle:@"继续下单" rightTitle:@"去支付" type:1 myBlock:^(NSInteger tag) {
                if(tag == 1){
                    
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"kNotificationGoToPay" object:nil];
                    self.tabBarController.selectedIndex = 1;
                    
                }else if (tag == 0){
                    QPerfectOrderInforMationVC *vc = [[QPerfectOrderInforMationVC alloc] init];
                    [self.navigationController pushViewController:vc animated:YES];
                    vc.nopaycount = [QUserInfo sharedInfo].unPayCount;
                }
            }];
            
        }else{
            QPerfectOrderInforMationVC *vc = [[QPerfectOrderInforMationVC alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        }
        
    }
}

#pragma mark -TableViewDataSource && TableViewdelegate

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell *cell = [[UITableViewCell alloc]init];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.backgroundColor = [UIColor redColor];
//    if (indexPath.row == 0) {
//        cell.userInteractionEnabled = YES;
//        _headView.frame = cell.bounds;
//        [cell addSubview:_headView];
//    }
    if (indexPath.row == 0) {
        _midView.frame = cell.bounds;
        [cell addSubview:_midView];
    }
    if (indexPath.row == 1) {
        _bottomView.frame = cell.bounds;
        [cell addSubview:_bottomView];
    }
    
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
//    if (indexPath.row == 0) {
//
//        return 230;
//
//    }
    if (indexPath.row == 0) {
       
        return 190;
    }
    if (indexPath.row == 1) {
        
        return 250;
    }
    return 0;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 2;
}
//- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
//
//    return _headView;
//}
//- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
//
//    return 230;
//}
#pragma mark --用户是否登陆
- (void)notLogin{
    
    [QViewUtility showAlertChooseViewWithImage:[UIImage imageNamed:@"smile_image"] content:@"您还未登录,请登录" leftTitle:@"取消" rightTitle:@"立即登录" type:1 myBlock:^(NSInteger tag) {
        if(tag == 1){
            QLoginVC *vc = [[QLoginVC alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        }
    }];
}
#pragma mark --- 定位
- (void)setLocationManager{
    self.locationManager = [[AMapLocationManager alloc] init];
    [self.locationManager setDelegate:self];
    [self.locationManager startUpdatingLocation];
    _search = [[AMapSearchAPI alloc] init];
    _search.delegate = self;
}

#pragma mark --- 定位成功
- (void)amapLocationManager:(AMapLocationManager *)manager didUpdateLocation:(CLLocation *)location{
    [self.locationManager stopUpdatingLocation];
    AMapPOIAroundSearchRequest *request = [[AMapPOIAroundSearchRequest alloc] init];
    request.location = [AMapGeoPoint locationWithLatitude:location.coordinate.latitude longitude:location.coordinate.longitude];
    request.offset = 1;
    request.requireExtension = YES;
    [QUserInfo sharedInfo].lat = [NSString stringWithFormat:@"%lf",location.coordinate.latitude];;
    [QUserInfo sharedInfo].lon = [NSString stringWithFormat:@"%lf",location.coordinate.longitude];;
    [_search AMapPOIAroundSearch:request];
}
#pragma mark --- 定位失败
- (void)amapLocationManager:(AMapLocationManager *)manager didFailWithError:(NSError *)error{
    [self.locationManager stopUpdatingLocation];
}
#pragma mark --- 实现POI搜索结果
- (void)onPOISearchDone:(AMapPOISearchBaseRequest *)request response:(AMapPOISearchResponse *)response{
    if(response.pois.count == 0){
        return;
    }
    AMapPOI *p = response.pois[0];
    [QUserInfo sharedInfo].cityStr = p.city;
    [QUserInfo sharedInfo].districtStr = p.district;
    [QUserInfo sharedInfo].address = p.address;
    
    CLog(@"市===%@  区===%@ ==%@",[QUserInfo sharedInfo].cityStr,[QUserInfo sharedInfo].districtStr,p.address);
}
ARRAY_INIT(bottomArray);
ARRAY_INIT(imgvoArr);
ARRAY_INIT(newsArr);
@end
